<template>
  <a-modal
    v-model:visible="visible"
    draggable
    width="500px"
    @cancel="cancelMethod"
    @before-ok="handleBeforeOk"
  >
    <template #title>
      {{
        formData.id
          ? `${$t('columns.operations.edit')}`
          : `${$t('searchTable.operation.create')}`
      }}凭证规则
    </template>
    <a-form
      ref="formRef"
      :label-col-props="{ span: 6 }"
      :model="formData"
      :wrapper-col-props="{ span: 18 }"
      class="form"
    >
      <div>
        <a-form-item
          :rules="[{ required: true, message: '请输入名称' }]"
          field="name"
          label="名称"
        >
          <a-input v-model="formData.name" placeholder="请输入名称" />
        </a-form-item>
      </div>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { createRule, VoucherRuleDTO } from '@/api/invoice';
  import { useRoute } from 'vue-router';

  defineProps({
    title: {
      type: String,
      default: '凭证配置',
    },
  });
  const formRef = ref();
  const visible = ref(false);
  const routeType = useRoute().meta.type;
  const routeTypeName = useRoute().meta.typeName;
  const formData = ref<VoucherRuleDTO>({
    accountSetId: '',
    accountSetName: '',
    bankCode: '',
    bodyType: '',
    chargeTypeList: [],
    departmentList: [],
    enableFlag: '',
    id: '',
    invoiceTypeList: [],
    name: '',
    payWayList: [],
    ruleItemList: [],
    typeId: '',
    typeName: '',
  });

  function handleChangeVisible() {
    visible.value = !visible.value;
    formData.value = {
      accountSetId: '',
      accountSetName: '',
      bankCode: '',
      bodyType: '',
      chargeTypeList: [],
      departmentList: [],
      enableFlag: '',
      id: '',
      invoiceTypeList: [],
      name: '',
      payWayList: [],
      ruleItemList: [],
      typeId: '',
      typeName: '',
    };
  }

  const cancelMethod = () => {
    visible.value = false;
  };
  const emit = defineEmits(['refresh']);

  function handleBeforeOk(done: any) {
    formRef.value.validate((valid: any) => {
      if (valid) {
        done(false);
      } else {
        formData.value.typeId = routeType as string;
        formData.value.typeName = routeTypeName as string;
        createRule(formData.value)
          .then(() => {
            Message.success('操作成功');
            emit('refresh');
            done();
          })
          .catch(() => {
            done(false);
          });
      }
    });
  }

  defineExpose({ handleChangeVisible });
</script>
